import {
  Controller,
  Post,
  UploadedFiles,
  Body,
  Get,
  UseInterceptors,
} from '@nestjs/common';
import { UploadService } from './upload.service';
import { FilesInterceptor } from '@nestjs/platform-express';
import fs from 'fs';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  // 分片上传
  @Post('/slice')
  @UseInterceptors(
    FilesInterceptor('files', 20, {
      dest: './uploads',
    }),
  )
  async upload(
    @UploadedFiles() files: Array<Express.Multer.File>,
    @Body() body,
  ) {
    const fileName = body.name.match(/(.+)\-\d+$/)[1];
    const chunkDir = 'uploads/chunks_' + fileName;

    // 用文件名来建立文件夹
    if (!fs.existsSync(chunkDir)) {
      fs.mkdirSync(chunkDir);
    }
    // 然后把所有分片都移动到这个文件夹下
    fs.renameSync(files[0].path, `${chunkDir}/${body.name}`);
  }

  // 合并分片
  @Post('merge')
  async merge(@Body() body) {
    // 根据名字查找对应的文件夹，拿到下面的所有文件
    const chunkDir = 'uploads/chunks_' + body.name;
    const files = fs.readdirSync(chunkDir);
    // 遍历所有的文件，读入一个新文件中，然后把之前文件夹删除
    let startPos = 0;
    let count = 0;
    files.map((file) => {
      const filePath = chunkDir + '/' + file;
      const stream = fs.createReadStream(filePath);
      stream
        .pipe(
          fs.createWriteStream('uploads/' + body.name, {
            start: startPos,
          }),
        )
        .on('finish', () => {
          count++;
          if (count === files.length) {
            fs.rm(chunkDir, { recursive: true }, () => {});
          }
        });
      startPos += fs.statSync(filePath).size;
    });
  }

  // 获取 OSS 临时上传凭证
  @Get('/getOssToken')
  async getOssToken() {
    return await this.uploadService.getOssPolicy();
  }
}
